<?php


namespace services\base;

use common\helpers\RedisHelper;
use common\models\linkedcare\LinkedcareChannel;
use common\models\linkedcare\LinkedcareTags;
use common\models\member\Member;
use services\log\LogMemberOpService;
use services\member\MemberService;
use Yii;
use common\components\Service;
use common\helpers\CommonHelper;
use common\models\base\TreatmentProject;

class TreatmentProjectService extends Service
{
    /**
     * 业务项目列表
     *
     * @param array $params
     * @param int $page
     * @param int $pageSize
     * @return array
     */
    public function treatmentProjectList(array $params, int $page, int $pageSize): array
    {
        $query = TreatmentProject::find()
            ->alias('tp')
            ->select(['tp.*', 'lt.name tag_name'])
            ->leftJoin(LinkedcareTags::tableName() . ' lt', 'tp.tag_id = lt.id')
            ->where([
                'tp.status' => [
                    TreatmentProject::STATUS_ENABLE,
                    TreatmentProject::STATUS_INVALID
                ],
            ])->groupBy('tp.id');
        // 搜索E看牙项目ID/ 名称
        if (isset($params['keywords']) && $params['keywords']) {
            if (is_numeric($params['keywords'])) {
                $query->andWhere(['like', 'tp.tag_id', "{$params['keywords']}%", false]);
            } else {
                $query->andWhere(['like', 'tp.name', $params['keywords']]);
            }
        }
        $list = $this->getListPageRes($query, $page, $pageSize, ['tp.status' => SORT_DESC, 'tp.sort' => SORT_ASC, 'tp.id' => SORT_DESC]);
        foreach ($list['list'] as &$val) {
            $val['status_name'] = TreatmentProject::$statuss[$val['status']] ?? '';
        }
        return $list;
    }

    /**
     * 状态下拉筛选项
     * @return array[]
     */
    public static function getStatusCondition(): array
    {
        return [
            ['value' => TreatmentProject::STATUS_ENABLE, 'label' => TreatmentProject::$statuss[TreatmentProject::STATUS_ENABLE]],
            ['value' => TreatmentProject::STATUS_INVALID, 'label' => TreatmentProject::$statuss[TreatmentProject::STATUS_INVALID]],
        ];
    }

    /**
     * 更新业务项目
     * @throws \Exception
     */
    public function updateTreatmentProject(array $params)
    {
        $treatmentProject = new TreatmentProject();
        $scenario = 'create';
        $oldTreatmentProject = null;
        // 是否为编辑，编辑判断排除当前ID
        $whereId = [];
        if ($params['id']) {
            $whereId = ['!=', 'id', $params['id']];
            // 业务项目表
            $oldTreatmentProject = self::getData($params['id']);
            $treatmentProject = TreatmentProject::findOne($params['id']);
            $scenario = 'edit';
        }
        // 判断名称是否存在
        $check = TreatmentProject::find()
            ->select(['id'])
            ->where([
                'name' => $params['name'],
                'status' => [TreatmentProject::STATUS_ENABLE, TreatmentProject::STATUS_INVALID]
            ])
            ->andWhere($whereId)
            ->asArray()
            ->one();
        if ($check) {
            return CommonHelper::api(422, '名称已存在');
        }

        $transaction = Yii::$app->db->beginTransaction();
        try {
            $treatmentProject->name = $params['name'];
            $treatmentProject->tag_id = $params['tag_id'] ?: 0;
            $treatmentProject->sort = $params['sort'] ?: 100;
            $treatmentProject->status = $params['status'] ?? TreatmentProject::STATUS_ENABLE;
            $treatmentProject->saveAndCheckResult();

            // 添加日志
            LogMemberOpService::createTreatmentProjectLog($scenario, $treatmentProject, $oldTreatmentProject);

            // 更新缓存
            RedisHelper::setTreatmentProject($treatmentProject);
            $transaction->commit();
            return ['id' => $treatmentProject->id];
        } catch (\Exception $e) {
            $transaction->rollBack();
            throw $e;
        }
    }

    /**
     * 业务项目
     * @param int $id
     * @return TreatmentProject|null
     */
    public static function getData(int $id): ?TreatmentProject
    {
        return TreatmentProject::findOne($id);
    }

    /**
     * 业务项目删除
     */
    public function deleteTreatmentProject(array $params): array
    {
        $transaction = Yii::$app->db->beginTransaction();
        try {
            // 更新业务项目状态为-1
            TreatmentProject::updateAll([
                'status' => TreatmentProject::STATUS_DELETE,
                'updated_at' => time()
            ], ['id' => $params['id']]);

            // 添加日志
            LogMemberOpService::createTreatmentProjectLog('delete', self::getData($params['id']));
            // 删除缓存
            RedisHelper::delTreatmentProject($params['id']);
            $transaction->commit();
            return ['id' => $params['id']];
        } catch (\Exception $e) {
            $transaction->rollBack();
            throw $e;
        }
    }

    /**
     * 根据Ids获取列表【禁用 + 正常】
     * @param array|null $ids
     * @return TreatmentProject[]
     */
    public static function getNormalListByIds(?array $ids = null, $orId = []): array
    {
        $query = TreatmentProject::find()
            ->select(['*'])
            ->where([
                'status' => [TreatmentProject::STATUS_INVALID, TreatmentProject::STATUS_ENABLE],
            ]);
        if (!is_null($ids)) {
            $query->andWhere(['id' => $ids]);
        }
        if ($orId) {
            $query->orWhere([
                'id' =>$orId,
                'status' => [TreatmentProject::STATUS_INVALID, TreatmentProject::STATUS_ENABLE],
            ]);
        }
        return $query->orderBy(['sort' => SORT_ASC, 'id' => SORT_ASC])->all();
    }

    /**
     * 获取正常
     * @param array|int|null $orIds
     * @return TreatmentProject[]
     */
    public static function getEnableListByIds($orIds = null): array
    {
        $query = TreatmentProject::find()
            ->select(['*'])
            ->where(['status' => TreatmentProject::STATUS_ENABLE]);
        if (!is_null($orIds)) {
            $query->orWhere(['id' => $orIds, 'status' => [TreatmentProject::STATUS_INVALID, TreatmentProject::STATUS_ENABLE]]);
        }
        return $query->orderBy(['id' => SORT_ASC])->all();
    }

    /**
     * 获取列表筛选项
     * @return array
     */
    public static function getListCondition(): array
    {
        return CommonHelper::getListCondition(self::getNormalListByIds(), ['value_column' => 'id', 'label_column' => 'name']);
    }

    /**
     * 获取编辑筛选项
     * @param int $type
     * @param int|array|null $orIds
     * @return array
     */
    public static function getEditCondition($orIds = null): array
    {
        return CommonHelper::getListCondition(self::getEnableListByIds($orIds), ['value_column' => 'id', 'label_column' => 'name']);
    }
}
